package org.shj.thread.basic;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.shj.thread.util.Util;

/**
 * Exchanger 可以用于遗传算法。遗传算法里需要选出两个人作为交配对象，这时候会交换两人的数据，并使用交叉规则得出2个交配结果。
 * Exchanger 也可以用于校对工作。 可以用于较对两个人的录入是否相同。
 * 
 * @author huangjian
 *
 */
public class ExchangeDemo {

	static Exchanger<String> exchanger = new Exchanger<String>();
	static ExecutorService executor = Executors.newCachedThreadPool();
	
	public static void main(String[] args) throws Exception{
		executor.execute(new Runnable(){
			public void run(){
				try{
					String a = "银行流水A";
					String b = exchanger.exchange(a);
					System.out.println("Got " + b + " from other threadB.");
				}catch(Exception e){
					
				}
			}
		});
		
		executor.execute(new Runnable(){
			public void run(){
				try{
					String b = "银行流水B";
					String a = exchanger.exchange(b);
					System.out.println("Got " + a + " from other threadA.");
				}catch(Exception e){
					
				}
			}
		});
		
		executor.shutdown();
		System.out.println("1111");
		Util.sleep(2);
		executor.awaitTermination(5, TimeUnit.SECONDS);
	}
}
